﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MvCameraControl;
using System.Threading;
using System.IO;
using System.Reflection.Emit;
using System.Drawing.Imaging;
using DMC300Axis_IO.Function;
using csLTDMC;
using OCR.Config;
using OCR.SystemThread;

namespace OCR
{
    internal class CameraReceiveThread
    {
        static readonly DeviceTLayerType enumTLayerType = DeviceTLayerType.MvGigEDevice | DeviceTLayerType.MvUsbDevice
| DeviceTLayerType.MvGenTLGigEDevice | DeviceTLayerType.MvGenTLCXPDevice | DeviceTLayerType.MvGenTLCameraLinkDevice | DeviceTLayerType.MvGenTLXoFDevice;

        public static List<IDeviceInfo> deviceInfoList = new List<IDeviceInfo>();
        public static IDevice device = null;

        public static bool isGrabbing = false;        // ch:是否正在取图 | en: Grabbing flag
        static Thread receiveThread = null;    // ch:接收图像线程 | en: Receive image thread

        public static IFrameOut frameForSave;                         // ch:获取到的帧信息, 用于保存图像 | en:Frame for save image
        public static readonly object saveImageLock = new object();

        public static void CameraInitialize()
        {
            SDKSystem.Initialize();

            RefreshDeviceList();

            Control.CheckForIllegalCrossThreadCalls = false;






            //ContinuousMotion();//连续运动
        }

        // ch:显示错误信息 | en:Show error message
        public static void ShowErrorMsg(string message, int errorCode)
        {
            string errorMsg;
            if (errorCode == 0)
            {
                errorMsg = message;
            }
            else
            {
                errorMsg = message + ": Error =" + String.Format("{0:X}", errorCode);
            }

            switch (errorCode)
            {
                case MvError.MV_E_HANDLE: errorMsg += " Error or invalid handle "; break;
                case MvError.MV_E_SUPPORT: errorMsg += " Not supported function "; break;
                case MvError.MV_E_BUFOVER: errorMsg += " Cache is full "; break;
                case MvError.MV_E_CALLORDER: errorMsg += " Function calling order error "; break;
                case MvError.MV_E_PARAMETER: errorMsg += " Incorrect parameter "; break;
                case MvError.MV_E_RESOURCE: errorMsg += " Applying resource failed "; break;
                case MvError.MV_E_NODATA: errorMsg += " No data "; break;
                case MvError.MV_E_PRECONDITION: errorMsg += " Precondition error, or running environment changed "; break;
                case MvError.MV_E_VERSION: errorMsg += " Version mismatches "; break;
                case MvError.MV_E_NOENOUGH_BUF: errorMsg += " Insufficient memory "; break;
                case MvError.MV_E_UNKNOW: errorMsg += " Unknown error "; break;
                case MvError.MV_E_GC_GENERIC: errorMsg += " General error "; break;
                case MvError.MV_E_GC_ACCESS: errorMsg += " Node accessing condition error "; break;
                case MvError.MV_E_ACCESS_DENIED: errorMsg += " No permission "; break;
                case MvError.MV_E_BUSY: errorMsg += " Device is busy, or network disconnected "; break;
                case MvError.MV_E_NETER: errorMsg += " Network error "; break;
            }

            MessageBox.Show(errorMsg, "PROMPT");
        }
        //刷新设备列表
        public static void RefreshDeviceList()
        {
            // ch:创建设备列表 | en:Create Device List

            int nRet = DeviceEnumerator.EnumDevices(enumTLayerType, out deviceInfoList);
            if (nRet != MvError.MV_OK)
            {
                ShowErrorMsg("Enumerate devices fail!", nRet);
                return;
            }

            //string tempDeviceInfo=string.Empty;
            //for (int i = 0; i < deviceInfoList.Count; i++)
            //{
            //    Console.WriteLine(deviceInfoList[i].SerialNumber);
            //    if (deviceInfoList[i].UserDefinedName != "")
            //    {
            //        tempDeviceInfo = tempDeviceInfo
            //            + deviceInfoList[i].TLayerType.ToString() + ": " + deviceInfoList[i].UserDefinedName + " (" + deviceInfoList[i].SerialNumber + ")\r\n";
            //    }
            //    else
            //    {
            //        tempDeviceInfo = tempDeviceInfo
            //            + deviceInfoList[i].TLayerType.ToString() + ": " + deviceInfoList[i].UserDefinedName + " (" + deviceInfoList[i].SerialNumber + ")\r\n";
            //    }
            //    File.WriteAllText("DeviceInfo.txt", tempDeviceInfo);
            //}


            OpenDevice();//打开相机

           
        }
        public static void RefreshDeviceListNoOpen()
        {
            //Console.WriteLine("相机列表刷新");
            // ch:创建设备列表 | en:Create Device List

            int nRet = DeviceEnumerator.EnumDevices(enumTLayerType, out deviceInfoList);
            if (nRet != MvError.MV_OK)
            {
                ShowErrorMsg("Enumerate devices fail!", nRet);
                return;
            }
            //判断有无设备
            if (deviceInfoList.Count == 0)
            {
                //ShowErrorMsg("No device, please select", 0);
                Console.WriteLine("设备列表个数为0");
                if (isGrabbing)
                {
                    isGrabbing = false;
                    receiveThread.Join();
                }
                if (device != null)
                {
                    device.Close();
                    device.Dispose();
                }
                device = null;
                //SDKSystem.Finalize();
            }
            else
            {
                //Console.WriteLine("设备列表个数不为0");
                bool hasCameraSerialNumber = Array.Exists(deviceInfoList.ToArray(), item => item.SerialNumber == LocalInfo.CameraSerialNumber);
                if (!hasCameraSerialNumber)
                {
                    Console.WriteLine("无指定设备");
                    if (isGrabbing)
                    {
                        isGrabbing = false;
                        receiveThread.Join();
                    }
                    if (device != null)
                    {
                        device.Close();
                        device.Dispose();
                    }
                    device = null;
                    //SDKSystem.Finalize();
                }

            }
        }
        public static void OpenDevice()
        {
            //判断有无设备
            if (deviceInfoList.Count == 0)
            {
                ShowErrorMsg("No device, please select", 0);
                OCR_Form.LightStateDo(9);
                return;
            }
            bool hasCameraSerialNumber = Array.Exists(deviceInfoList.ToArray(), item => item.SerialNumber == LocalInfo.CameraSerialNumber);

            Console.WriteLine("hasCameraSerialNumber: " + hasCameraSerialNumber);
            if (!hasCameraSerialNumber)
            {
                //OCR_Form.oCR_Form.richTB_State_PLC.AppendText("未找到对应序列号的相机..." + DateTime.Now.ToString("yyyy-MM-dd-HH:mm:ss") + "\r\n");
                OCR_Form.AppendLog("未找到对应序列号的相机..." + DateTime.Now.ToString("yyyy-MM-dd-HH:mm:ss"), isError: true);
                return;
            }
            // 获取选择的设备信息 
            int tempDeviceIndex = -1;
            Console.WriteLine("LocalInfo.CameraSerialNumber:"+LocalInfo.CameraSerialNumber);
            for (int i = 0; i < deviceInfoList.Count; i++)
            {
                Console.WriteLine("deviceInfoList[i].SerialNumber:" + deviceInfoList[i].SerialNumber);
                if (deviceInfoList[i].SerialNumber == LocalInfo.CameraSerialNumber)
                {
                    tempDeviceIndex = i;
                }
            }
            if (tempDeviceIndex < 0)
                return;
            IDeviceInfo deviceInfo = deviceInfoList[tempDeviceIndex];
            try
            {
                // 打开设备
                device = DeviceFactory.CreateDevice(deviceInfo);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Create Device fail!" + ex.Message);
                return;
            }


            int result = device.Open();
            if (result != MvError.MV_OK)
            {
                ShowErrorMsg("Open Device fail!", result);
                return;
            }

            //ch: 判断是否为gige设备 | en: Determine whether it is a GigE device
            if (device is IGigEDevice)
            {
                //ch: 转换为gigE设备 | en: Convert to Gige device
                IGigEDevice gigEDevice = device as IGigEDevice;

                // ch:探测网络最佳包大小(只对GigE相机有效) | en:Detection network optimal package size(It only works for the GigE camera)
                int optionPacketSize;
                result = gigEDevice.GetOptimalPacketSize(out optionPacketSize);
                if (result != MvError.MV_OK)
                {
                    ShowErrorMsg("Warning: Get Packet Size failed!", result);
                }
                else
                {
                    result = device.Parameters.SetIntValue("GevSCPSPacketSize", (long)optionPacketSize);
                    if (result != MvError.MV_OK)
                    {
                        ShowErrorMsg("Warning: Set Packet Size failed!", result);
                    }
                }
            }
            device.Parameters.SetEnumValueByString("TriggerMode", "On");
            device.Parameters.SetEnumValueByString("TriggerSource", "Line0");
            // ch:设置采集连续模式 | en:Set Continues Aquisition Mode
            //device.Parameters.SetEnumValueByString("AcquisitionMode", "Continuous");
            //device.Parameters.SetEnumValueByString("TriggerMode", "Off");

            StartGrab();//开始抓图
        }
        public static void StartGrab()
        {
            try
            {
                // ch:标志位置位true | en:Set position bit true
                isGrabbing = true;

                receiveThread = new Thread(ReceiveThreadProcess);
                receiveThread.Start();
                //MessageBox.Show("抓取线程开启");
                OCR_Form.oCR_Form.richTB_State_PLC.AppendText("相机抓取线程开启..." + DateTime.Now.ToString("yyyy-MM-dd-HH:mm:ss") + "\r\n");
                //if (OCR_Form.oCR_Form.richTB_State_PLC.Text != string.Empty)
                //{
                //    OCR_Form.oCR_Form.richTB_State_PLC.AppendText("\r\n相机抓取线程开启..." + DateTime.Now.ToString("yyyy-MM-dd-HH:mm:ss"));
                //}
                //else
                //{
                //    OCR_Form.oCR_Form.richTB_State_PLC.AppendText("相机抓取线程开启..." + DateTime.Now.ToString("yyyy-MM-dd-HH:mm:ss") + "\r\n");
                //}

            }
            catch (Exception ex)
            {
                MessageBox.Show("Start thread failed!, " + ex.Message);
                throw;
            }

            // ch:开始采集 | en:Start Grabbing
            int result = device.StreamGrabber.StartGrabbing();
            //MessageBox.Show("开始抓取");
            OCR_Form.oCR_Form.richTB_State_PLC.AppendText("相机开始抓取..." + DateTime.Now.ToString("yyyy-MM-dd-HH:mm:ss")+ "\r\n");

            if (result != MvError.MV_OK)
            {
                isGrabbing = false;
                receiveThread.Join();
                ShowErrorMsg("Start Grabbing Fail!", result);
                return;
            }


        }
        public static void StopGrab() 
        {
            // ch:标志位设为false | en:Set flag bit false
            isGrabbing = false;
            receiveThread.Join();

            // ch:停止采集 | en:Stop Grabbing
            int result = device.StreamGrabber.StopGrabbing();
            if (result != MvError.MV_OK)
            {
                ShowErrorMsg("Stop Grabbing Fail!", result);
            }
        }

        public static void CloseDevice()
        {
            // ch:取流标志位清零 | en:Reset flow flag bit
            if (isGrabbing == true)
            {
                StopGrab();
            }
            // ch:关闭设备 | en:Close Device
            if (device != null)
            {
                device.Close();
                device.Dispose();
            }
            SDKSystem.Finalize();
            // ch:控件操作 | en:Control Operation
            //SetCtrlWhenClose();
        }

        public static bool isImageData;
        public static DateTime imageDateTime;
        public static void ReceiveThreadProcess()
        {
            int nRet;

            Graphics graphics;   // ch:使用GDI在pictureBox上绘制图像 | en:Display frame using a graphics

            while (isGrabbing)
            {
                IFrameOut frameOut;

                DateTime GrabImgTime = DateTime.Now;
                nRet = device.StreamGrabber.GetImageBuffer(1000, out frameOut);
                //Console.WriteLine("image null  " + (frameOut.Image != null).ToString());
                DateTime GetImgTime = DateTime.Now;
                //Console.WriteLine("抓到图的时长: " + (GetImgTime - GrabImgTime).TotalMilliseconds);
                if (MvError.MV_OK == nRet)
                {

                    lock (saveImageLock)
                    {


                        //Console.WriteLine("取到图 " + +getImgTime.TimeOfDay);
                        //string temp = string.Format("Height:{0} -Width:{1} -ImageSize:{2} -PixelData:{3 }-PixelDataPtr:{4} -PixelType:{5} -PixelDataLength:{6}",
                        //   frameOut.Image.Height, frameOut.Image.Width, frameOut.Image.ImageSize, frameOut.Image.PixelData, frameOut.Image.PixelDataPtr, frameOut.Image.PixelType, frameOut.Image.PixelData.Length);
                        //Console.WriteLine("Height:{0} -Width:{1} -ImageSize:{2} -PixelData:{3 }-PixelDataPtr:{4} -PixelType:{5}",
                        //    frameOut.Image.Height, frameOut.Image.Width, frameOut.Image.ImageSize, frameOut.Image.PixelData, frameOut.Image.PixelDataPtr, frameOut.Image.PixelType);
                        //Console.WriteLine(temp);
                        //foreach (byte b in frameOut.Image.PixelData)
                        //{
                        //    Console.WriteLine(b+"\r");
                        //}
                        //if (CameraTriggerTime_Config.SaveOriginalImageCh)
                        //{
                        //    try
                        //    {
                        //        ImageFormatInfo imageFormatInfo = new ImageFormatInfo();
                        //        imageFormatInfo.FormatType = ImageFormatType.Bmp;
                        //        string ImagePath = @"out\\" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + "Original" + ".bmp";
                        //        device.ImageSaver.SaveImageToFile(ImagePath, frameOut.Image, imageFormatInfo, CFAMethod.Equilibrated);
                        //    }
                        //    catch (Exception ex)
                        //    {
                        //        return;
                        //    }
                        //}
                        DateTime getImgTime = DateTime.Now;
                        frameForSave = frameOut.Clone() as IFrameOut;
                        DateTime cloneImgTime = DateTime.Now;
                        //Console.WriteLine("clone: " + +cloneImgTime.TimeOfDay);
                        Console.WriteLine("clone时长: "+(cloneImgTime - getImgTime).TotalMilliseconds);
                        if (frameForSave.Image == null)
                            return;
                        isImageData = true;

                        imageDateTime = DateTime.Now;
                        Console.WriteLine("ReceiveThreadProcess-拿到图："+ imageDateTime.ToString("yyyy:MM:dd:HH:mm:ss:ffff"));

                        string temp1 = string.Format("Height:{0} -Width:{1} -ImageSize:{2} -PixelData:{3 }-PixelDataPtr:{4} -PixelType:{5} -PixelDataLength:{6}",
                           frameForSave.Image.Height, frameForSave.Image.Width, frameForSave.Image.ImageSize, frameForSave.Image.PixelData, frameForSave.Image.PixelDataPtr, frameForSave.Image.PixelType, frameForSave.Image.PixelData.Length);
                        Console.WriteLine(temp1);
                        //if(OCR_Form.softwareType == "0")
                        //{
                            //AlgorithmModule.SaveWrongImg(frameForSave);
                        //}


                        //foreach (byte b in frameForSave.Image.PixelData)
                        //{
                        //    //Console.WriteLine(b + "\r");
                        //}

                        //Console.WriteLine("AverageBrightness:{0}-Blue:{1}-ChunkInfo:{2}-CycleCount:{3}-CycleOffset:{4}-DevTimeStamp:{5}-ExposureTime:{6}-FrameCount:{7}" +
                        //"-FrameLen:{8}-FrameNum:{9}-Gain:{10}-Green:{11}-HostTimeStamp:{12}-Image:{13}" +
                        //"-Input:{14}-LostPacket:{15}-OffsetX:{16}-OffsetY:{17}-Output:{18}-Red:{19}-SecondCount:{20}-TriggerIndex:{21}",
                        //frameOut.AverageBrightness, frameOut.Blue, frameOut.ChunkInfo, frameOut.CycleCount, frameOut.CycleOffset, frameOut.DevTimeStamp, frameOut.ExposureTime,
                        //frameOut.FrameCount, frameOut.FrameLen, frameOut.FrameNum, frameOut.Gain, frameOut.Green, frameOut.HostTimeStamp, frameOut.Image, frameOut.Input, frameOut.LostPacket,
                        //frameOut.OffsetX, frameOut.OffsetY, frameOut.Output, frameOut.Red, frameOut.SecondCount, frameOut.TriggerIndex
                        //);
                        Console.WriteLine("存图时间 " + DateTime.Now.TimeOfDay);

                        //if(frameForSave.Image.ImageSize== 2013760)
                        //{
                        //    isImageData = true;
                        //}

                    }

#if !GDI_RENDER
                    //device.ImageRender.DisplayOneFrame(OCR_Form.oCR_Form.mainCameraPb.Handle, frameOut.Image);

#else
                    // 使用GDI绘制图像
                    try
                    {
                        using (Bitmap bitmap = frameOut.Image.ToBitmap())
                        {
                            if (graphics == null)
                            {
                                graphics = pictureBox1.CreateGraphics();
                            }

                            Rectangle srcRect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
                            Rectangle dstRect = new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height);
                            graphics.DrawImage(bitmap, dstRect, srcRect, GraphicsUnit.Pixel);
                        }
                    }
                    catch (Exception e)
                    {
                        device.StreamGrabber.FreeImageBuffer(frameOut);
                        MessageBox.Show(e.Message);
                        return;
                    }
#endif


                    device.StreamGrabber.FreeImageBuffer(frameOut);
                }
                else
                {
                    //isImageData = false;

                    //if (bnTriggerMode.Checked)
                    //{
                    //    Thread.Sleep(5);
                    //}
                }
            }
        }


        private static void GetParam()
        {
            IFloatValue floatValue;
            int result = device.Parameters.GetFloatValue("ExposureTime", out floatValue);
            if (result == MvError.MV_OK)
            {
                //tbExposure.Text = floatValue.CurValue.ToString("F1");
            }

            result = device.Parameters.GetFloatValue("Gain", out floatValue);
            if (result == MvError.MV_OK)
            {
                //tbGain.Text = floatValue.CurValue.ToString("F1");
            }

            result = device.Parameters.GetFloatValue("ResultingFrameRate", out floatValue);
            if (result == MvError.MV_OK)
            {
                //tbFrameRate.Text = floatValue.CurValue.ToString("F1");
            }

            //cbPixelFormat.Items.Clear();
            IEnumValue enumValue;
            result = device.Parameters.GetEnumValue("PixelFormat", out enumValue);
            if (result == MvError.MV_OK)
            {
                foreach (var item in enumValue.SupportEnumEntries)
                {
                    //cbPixelFormat.Items.Add(item.Symbolic);
                    if (item.Symbolic == enumValue.CurEnumEntry.Symbolic)
                    {
                        //cbPixelFormat.SelectedIndex = cbPixelFormat.Items.Count - 1;
                    }
                }

            }
        }
        /// <summary>
        /// ch:获取触发模式 | en:Get Trigger Mode
        /// </summary>
        private void GetTriggerMode()
        {
            IEnumValue enumValue;
            int result = device.Parameters.GetEnumValue("TriggerMode", out enumValue);
            if (result == MvError.MV_OK)
            {
                if (enumValue.CurEnumEntry.Symbolic == "On")
                {
                    //bnTriggerMode.Checked = true;
                    //bnContinuesMode.Checked = false;

                    result = device.Parameters.GetEnumValue("TriggerSource", out enumValue);
                    if (result == MvError.MV_OK)
                    {
                        if (enumValue.CurEnumEntry.Symbolic == "TriggerSoftware")
                        {
                            //cbSoftTrigger.Enabled = true;
                            //cbSoftTrigger.Checked = true;
                            //if (isGrabbing)
                            //{
                            //    bnTriggerExec.Enabled = true;
                            //}
                        }
                    }
                }
                else
                {
                    //bnContinuesMode.Checked = true;
                    //bnTriggerMode.Checked = false;
                }
            }
        }


        //开始抓取触发流程
        public static void StartGrabTrigger()
        {
            //CameraTriggerThread.iCameraTrigger_Step = 10;
            if (LocalInfo.CheckDI == "0")
            {
                CameraTriggerThread.iCameraTrigger_Step = 22;
            }
            else if (LocalInfo.CheckDI == "1")
            {
                CameraTriggerThread.iCameraTrigger_Step = 10;
            }
            //DMC300_Info.CameraTrigger_IsStop = true;
            CameraTriggerTime_Config.CamearTriggerPause = false;

            MessageBox.Show("触发准备完成");
        }
        //停止抓取流程
        public static void StopGrabTrigger()
        {
            //DMC300_Info.CameraTrigger_IsStop = false;
        }
        //伺服始能
        private static void ServoStart()
        {
            if (LTDMC.dmc_read_sevon_pin(DMC300_Info.usCardId[0], 0) == 1)      //當讀取狀態為1時，當下始能未開啟
            {
                LTDMC.dmc_write_sevon_pin(DMC300_Info.usCardId[0], 0, 0);       //下達0時是開啟始能
            }
            else
            {
                LTDMC.dmc_write_sevon_pin(DMC300_Info.usCardId[0], 0, 1);       ////下達1時是關閉始能
            }
        }
        //正向连续运动
        public static void ContinuousMotion()
        {
            ushort usAxis = 0; //轴号
            double dStartVel=100;           //起始速度
            double dMaxVel=10000;             //运行速度
            double dTacc=0.5;               //加速时间
            double dTdec=0.5;               //减速时间
            double dStopVel=100;            //停止速度
            double dSpara=0.2;              //S段时间       
            ushort usDir=1;               //运动方向

            LTDMC.dmc_set_profile(DMC300_Info.usCardId[0], usAxis, dStartVel, dMaxVel, dTacc, dTdec, dStopVel);//设置速度参数
            LTDMC.dmc_set_s_profile(DMC300_Info.usCardId[0], usAxis, 0, dSpara);                                    //设置S段速度参数
            LTDMC.dmc_vmove(DMC300_Info.usCardId[0], usAxis, usDir);
        }
        //反向连续运动
        public static void BackContinuousMotion()
        {
            ushort usAxis = 0; //轴号
            double dStartVel = 100;           //起始速度
            double dMaxVel = 10000;             //运行速度
            double dTacc = 0.5;               //加速时间
            double dTdec = 0.5;               //减速时间
            double dStopVel = 100;            //停止速度
            double dSpara = 0.2;              //S段时间       
            ushort usDir = 0;               //运动方向

            LTDMC.dmc_set_profile(DMC300_Info.usCardId[0], usAxis, dStartVel, dMaxVel, dTacc, dTdec, dStopVel);//设置速度参数
            LTDMC.dmc_set_s_profile(DMC300_Info.usCardId[0], usAxis, 0, dSpara);                                    //设置S段速度参数
            LTDMC.dmc_vmove(DMC300_Info.usCardId[0], usAxis, usDir);
        }
        //停止运动
        public static void StopMotion()
        {
            ushort usAxis = 0;                             //轴号
            ushort usStopMode = 0;                                 //制动方式，0：减速停止，1：紧急停止
            double dTdec = Double.Parse("0.5");       //减速时间         
            LTDMC.dmc_set_dec_stop_time(DMC300_Info.usCardId[0], usAxis, dTdec);  //设置减速停止时间
            LTDMC.dmc_stop(DMC300_Info.usCardId[0], usAxis, usStopMode);
        }

        public static void StartGrabTrigger_Modbus()
        {
            CameraTriggerThread_Modbus.iCameraTrigger_Step = 5;
            //CameraTriggerTime_Config.CamearTriggerPause = false;

            //OCR_Form.oCR_Form.richTB_State_PLC.Text = string.Empty;
            OCR_Form.oCR_Form.richTB_State_PLC.AppendText("Modbus触发流程开始..." + DateTime.Now.ToString("yyyy-MM-dd-HH:mm:ss") + "\r\n");
            //if (OCR_Form.oCR_Form.richTB_State_PLC.Text!=string.Empty)
            //{
            //    OCR_Form.oCR_Form.richTB_State_PLC.AppendText("Modbus触发流程开始..." + DateTime.Now.ToString("yyyy-MM-dd-HH:mm:ss") + "\r\n");
            //}
            //else
            //{
            //    OCR_Form.oCR_Form.richTB_State_PLC.AppendText("Modbus触发流程开始..." + DateTime.Now.ToString("yyyy-MM-dd-HH:mm:ss") + "\r\n");
            //}
            //MessageBox.Show("Modbus触发准备完成");

        }
        public static void StopGrabTrigger_Modbus()
        {
            CameraTriggerThread_Modbus.iCameraTrigger_Step = 0;
            //CameraTriggerTime_Config.CamearTriggerPause = false;

            //OCR_Form.oCR_Form.richTB_State_PLC.Text = string.Empty;
            OCR_Form.oCR_Form.richTB_State_PLC.AppendText("Modbus触发流程停止..." + DateTime.Now.ToString("yyyy-MM-dd-HH:mm:ss") + "\r\n");
            //if (OCR_Form.oCR_Form.richTB_State_PLC.Text != string.Empty)
            //{
            //    OCR_Form.oCR_Form.richTB_State_PLC.AppendText("Modbus触发流程停止..." + DateTime.Now.ToString("yyyy-MM-dd-HH:mm:ss")+ "\r\n");
            //}
            //else
            //{
            //    OCR_Form.oCR_Form.richTB_State_PLC.AppendText("Modbus触发流程停止..." + DateTime.Now.ToString("yyyy-MM-dd-HH:mm:ss") + "\r\n");
            //}
            //MessageBox.Show("Modbus触发准备完成");

        }

        public static bool SwitchUserSet(uint userSetNumber)
        {
            if (device == null)
            {
                MessageBox.Show("相机未连接");
                return false;
            }
            StopGrab();


            try
            {
                int nRet = device.Parameters.SetEnumValue("UserSetSelector", userSetNumber);
                if (nRet != MvError.MV_OK)
                {
                    ShowErrorMsg("相机用户集设置失败", nRet);
                    return false;
                }
                nRet = device.Parameters.SetCommandValue("UserSetLoad");
                if (nRet != 0)
                {
                    MessageBox.Show($"相机加载用户集失败，错误代码: {nRet}");
                    return false;
                }
                nRet = device.Parameters.SetEnumValue("UserSetDefault", userSetNumber);
                if (nRet != MvError.MV_OK)
                {
                    ShowErrorMsg("相机默认用户集设置失败", nRet);
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"相机切换用户集时发生错误: {ex.Message}");
                return false;
            }
            StartGrab();
        }
    }
}
